#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2024 Huawei Technologies Co., Ltd. All rights reserved.

#[[ $# -eq 3 ]] || {
#	echo 'Rpm file and source rpm file path is required'

#	exit 99
#}
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
source "$SCRIPT_DIR/../lib/epkg/hash.sh"

rpm_file=$1
epkg_repo_path=$2
rpm_file_name=${rpm_file##*/}

epkg_conversion_dir="${HOME}/epkg_conversion"

init_conversion_dirs()
{
	rm -rf ${epkg_conversion_dir}/*

	mkdir -p ${epkg_conversion_dir}/{fs,info}
	mkdir -p ${epkg_conversion_dir}/info/pgp
	touch ${epkg_conversion_dir}/info/{package.json,buildinfo.json,files,runtimePhase.sh}
}

decompress_rpm()
{
	rpm2cpio ${rpm_file} | cpio -idm --quiet -D ${epkg_conversion_dir}/fs/ 2>/dev/null
}

generate_files()
{
	find ${epkg_conversion_dir}/fs/ -mindepth 1 -exec stat --format='%n mode=%a size=%s mtime=%Y' {} \; > ${epkg_conversion_dir}/info/files

	sed -i "s|^${epkg_conversion_dir}/fs/||" ${epkg_conversion_dir}/info/files
	# 生成package.json
	./gen-package.sh $rpm_file ${epkg_conversion_dir}/info/ /tmp/rpm
}

generate_epkg_name()
{
	local rpm_hash
	local rpm_name
	local rpm_ver
	local rpm_rel

	# 将hash改为hash.sh中的计算方法
	rpm_hash=$(rpm_hash ${rpm_file})
	read rpm_name rpm_ver rpm_rel <<< $(rpm -qp --qf '%{NAME} %{version} %{release}' ${rpm_file} 2>/dev/null)

	epkg_name="${rpm_hash}"__"${rpm_name}"__"${rpm_ver}"__"${rpm_rel}.epkg"

	mkdir -p ${epkg_repo_path}/pkg-info/
	# epkg_json_name=${rpm_hash}__${rpm_name}__${rpm_ver}__${rpm_rel}.json
	# cp ${epkg_conversion_dir}/info/package.json ${epkg_repo_path}/pkg-info/${epkg_json_name:0:2}/${epkg_json_name}
}

compress_epkg()
{
	mkdir -p ${epkg_repo_path}/store/${epkg_name:0:2}/
	tar --zstd -cvf ${epkg_repo_path}/store/${epkg_name:0:2}/${epkg_name} -C ${epkg_conversion_dir} .
}

init_conversion_dirs
decompress_rpm
generate_files
generate_epkg_name
compress_epkg
